package com.ohos.connent.bizscenecloud.biz.modular.dp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ohos.connent.accountcloud.auth.core.pojo.SaBaseLoginUser;
import com.ohos.connent.bizscenecloud.auth.core.util.StpLoginUserUtil;
import com.ohos.connent.bizscenecloud.biz.modular.dp.entity.BizDpProduct;
import com.ohos.connent.bizscenecloud.biz.modular.dp.entity.BizDpProductExamine;
import com.ohos.connent.bizscenecloud.biz.modular.dp.enums.ExamineEnum;
import com.ohos.connent.bizscenecloud.biz.modular.dp.enums.StatusEnum;
import com.ohos.connent.bizscenecloud.biz.modular.dp.enums.YesNoEnum;
import com.ohos.connent.bizscenecloud.biz.modular.dp.mapper.BizDpProductMapper;
import com.ohos.connent.bizscenecloud.biz.modular.dp.param.*;
import com.ohos.connent.bizscenecloud.biz.modular.dp.result.BizDpProductSettingResult;
import com.ohos.connent.bizscenecloud.biz.modular.dp.result.BizProCategoryDetailResult;
import com.ohos.connent.bizscenecloud.biz.modular.dp.result.DevicesInformationResult;
import com.ohos.connent.bizscenecloud.biz.modular.dp.service.BizDpProductExamineService;
import com.ohos.connent.bizscenecloud.biz.modular.dp.service.BizDpProductService;
import com.ohos.connent.bizscenecloud.biz.modular.dp.utils.Base36IncrementUtils;
import com.ohos.connent.bizscenecloud.biz.modular.dp.utils.RestTemplateHelper;
import com.ohos.connent.bizscenecloud.biz.modular.dp.utils.ZipFileUtils;
import com.ohos.connent.bizscenecloud.common.exception.CommonException;
import com.ohos.connent.bizscenecloud.common.pojo.CommonResult;
import com.ohos.connent.bizscenecloud.dev.api.DevConfigApi;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;



/**
 * 产品service类
 * @Author: ChenJiaHao
 * @Date: 2024/6/5 9:36
 * @Description:
 */
@Service
public class BizDpProductServiceImpl extends ServiceImpl<BizDpProductMapper, BizDpProduct> implements BizDpProductService {

    private static final String PROD_ID_KEY = "PROD_ID";
    private static final String PROD_ID_DISCOVERY_KEY = "PROD_ID_DISCOVERY";
    private static final String ROLE_CODE = "l7bd5ejl3q";

    private static final String DATA_VERSION_KEY = "DATA_VERSION";
    private static final String DEVICE_INFO_VERSION_KEY = "DEVICE_INFO_VERSION";

    private static final String DEVICE_INFO_ASSETS_PATH = "/device_info/assets";
    private static final String DEVICE_INFO_PATH = "/device_info";
    private static final String DEVICE_INFO_ZIP = "/device_info.zip";
    private static final String DEVICE_INFO_JSON = "/device_info/main_devices_information.json";
    private static final String DEVICE_INFO_VERSION = "/device_info/version.xml";

    private static final String DATA_IMAGE_PATH = "/data/image";
    private static final String DATA_PROFILE_PATH = "/data/main_help.json";
    private static final String DATA_VERSION_PATH = "/data/version.json";
    private static final String DATA_ZIP = "/data.zip";
    private static final String DATA_PATH = "/data";

    @Resource
    RestTemplateHelper restTemplateHelper;

    @Resource
    private DevConfigApi devConfigApi;

    @Autowired
    private BizDpProductExamineService bizDpProductExamineService;

    private static final Map<String, Map<String, String>> ICON_CACHE_MAP = new ConcurrentHashMap<>();

    @Override
    public List<Tree<String>> tree(BizDpProductTreeParam bizProCategoryDictTreeParam) {
        CommonResult commonResult = restTemplateHelper.getProCategoryTree(bizProCategoryDictTreeParam.getSearchKey());
        if (!commonResult.getCode().equals(CommonResult.CODE_SUCCESS)) {
            throw new CommonException(commonResult.getCode(), commonResult.getMsg());
        }
        return (List<Tree<String>>) commonResult.getData();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(@NotNull BizDpProductAddParam bizDpProductAddParam) {
        BizDpProduct resBizDpProduct = BeanUtil.copyProperties(bizDpProductAddParam, BizDpProduct.class);
        resBizDpProduct.setId(IdWorker.getIdStr()).setProdId(randomProdId(StringUtils.equals(resBizDpProduct.getSupportProximityDiscovery(), YesNoEnum.YES.getKey())));
        resBizDpProduct.setStatus(StatusEnum.TO_BE_SUBMITTED.getKey());
        this.save(resBizDpProduct);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(BizDpProductEditParam bizDpProductEditParam) {
        BizDpProduct bizDpProduct = this.queryEntity(bizDpProductEditParam.getId());
        if (Objects.isNull(bizDpProduct)) {
            throw new CommonException("产品不存在，id值为：{}", bizDpProductEditParam.getId());
        }
        if (StringUtils.equals(bizDpProduct.getStatus(), StatusEnum.APPROVED.getKey())) {
            throw new CommonException("产品已审核通过，不允许修改");
        }
        BizDpProduct resBizDpProduct = BeanUtil.copyProperties(bizDpProductEditParam, BizDpProduct.class);
        this.updateById(resBizDpProduct);
    }

    /**
     * 2025-05-30 生成规则修改 末位自增 36位进制  00001 {1-9-A-Z} Z0001 {1-9-A-Z} （支持靠近发现功能首位固定使用Z）
     * @return
     */
    private String randomProdId(Boolean isDiscovery) {
        int count = 0;
        String valueByKey = devConfigApi.getValueByKey(PROD_ID_KEY);
        if (Boolean.TRUE.equals(isDiscovery)) {
            valueByKey = devConfigApi.getValueByKey(PROD_ID_DISCOVERY_KEY);
        }
        String prodId = Base36IncrementUtils.incrementBase36(valueByKey);
        while (true) {
            BizDpProduct bizDpProduct = this.getOne(Wrappers.lambdaQuery(BizDpProduct.class).eq(BizDpProduct::getProdId, prodId));
            if (ObjectUtil.isEmpty(bizDpProduct)) {
                if (Boolean.TRUE.equals(isDiscovery) ) {
                    devConfigApi.updateValueByKey(PROD_ID_DISCOVERY_KEY, prodId);
                } else {
                    devConfigApi.updateValueByKey(PROD_ID_KEY, prodId);

                }
                return prodId;
            }
            prodId = Base36IncrementUtils.incrementBase36(prodId);
            count ++;
            if (count > 100) {
                throw new CommonException("ProdID生成失败");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void copy(BizDpProductIdParam bizDpProductIdParam) {
        BizDpProduct bizDpProduct = queryEntity(bizDpProductIdParam.getId());
        bizDpProduct.setId(IdWorker.getIdStr())
                .setProdId(randomProdId(StringUtils.equals( bizDpProduct.getSupportProximityDiscovery(), YesNoEnum.YES.getKey())))
                .setStatus(StatusEnum.TO_BE_SUBMITTED.getKey())
                .setSubmitTime(null);
        bizDpProduct.setCreateUser(null);
        bizDpProduct.setCreateTime(null);
        this.save(bizDpProduct);
    }

    @Override
    public BizDpProduct queryEntity(String id) {
        BizDpProduct bizDpProduct = this.getById(id);
        if(ObjectUtil.isEmpty(bizDpProduct)) {
            throw new CommonException("产品不存在，id值为：{}", id);
        }
        return bizDpProduct;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(BizDpProductIdParam bizDpProductIdParam) {
        BizDpProduct bizDpProduct = this.getById(bizDpProductIdParam.getId());
        if(ObjectUtil.isEmpty(bizDpProduct)) {
            throw new CommonException("产品不存在，id值为：{}", bizDpProductIdParam.getId());
        }
        if (StringUtils.equals(bizDpProduct.getStatus(), StatusEnum.APPROVED.getKey())) {
            throw new CommonException("产品已审核通过，不允许删除");
        }
        this.removeById(bizDpProductIdParam.getId());
    }

    @Override
    public BizDpProduct detail(BizDpProductIdParam bizDpProductIdParam) {
        BizDpProduct bizDpProduct = queryEntity(bizDpProductIdParam.getId());
        if (Objects.isNull(bizDpProduct)) {
            throw new CommonException("产品不存在，id值为：{}", bizDpProductIdParam.getId());
        }
        return bizDpProduct;
    }

    @Override
    public void geFileUploadIconId(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String suffix = ObjectUtil.isNotEmpty(originalFilename) ? StrUtil.subAfter(originalFilename, StrUtil.DOT, true) : null;
        if (ObjectUtil.isEmpty(suffix) || !isPic(Objects.requireNonNull(suffix))) {
            throw new CommonException("图片格式不符合要求");
        }
        InputStream inputStream = file.getInputStream();
        if (ObjectUtil.isEmpty(inputStream)) {
            throw new CommonException("图片解析失败");
        }
        BufferedImage image = ImageIO.read(inputStream);
         if (ObjectUtil.isEmpty(image)) {
            throw new CommonException("图片解析失败");
        }
         if (image.getWidth() > 256 && image.getHeight() > 256) {
             throw new CommonException("图片尺寸不符合要求");
         }

        String iconBase64 = null;
        try {
            iconBase64 = ImgUtil.toBase64(ImgUtil.scale(ImgUtil.toImage(file.getBytes()), 400, 400, null), suffix);
        } catch (Exception e) {
            log.error(">>> 图片解析失败：", e);
        }
        if (ObjectUtil.isEmpty(iconBase64)) {
            throw new CommonException("图片解析失败");
        }
        String imageId = getMD5(file);
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("iconBase64", iconBase64);
        hashMap.put("imageId", imageId);
        hashMap.put("originalFilename", originalFilename);
        ICON_CACHE_MAP.put("imageDetail", hashMap);
    }
    private static boolean isPic(String suffix) {
        String fileSuffix = suffix.toLowerCase();
        return ImgUtil.IMAGE_TYPE_PNG.equals(fileSuffix);
    }
    private String getMD5(MultipartFile file) {
        String md5Hex;
        try {
            md5Hex = DigestUtils.md5Hex(file.getBytes());
        } catch (Exception e) {
            // 如果md5值获取失败则用id，确保逻辑往下走
            log.error(">>> 解析图片获取MD5值失败：", e);
            md5Hex = IdWorker.getIdStr();
        }
        return md5Hex;
    }
    @Override
    public Page<BizDpProduct> page(BizDpProductPageParam bizDpProductPageParam) {
        Page<BizDpProduct> page = new Page<>(bizDpProductPageParam.getCurrent(), bizDpProductPageParam.getSize());
        QueryWrapper<BizDpProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(BizDpProduct::getId, BizDpProduct::getBrand, BizDpProduct::getName, BizDpProduct::getSubmitTime,
                BizDpProduct::getStatus,BizDpProduct::getType,BizDpProduct::getCategoryDictParentId);
        if (StringUtils.isNotBlank(bizDpProductPageParam.getStatus())) {
            queryWrapper.eq("status",bizDpProductPageParam.getStatus());
        } else {
            queryWrapper.in("status",
                    StatusEnum.TO_BE_REVIEWED.getKey(),
                    StatusEnum.APPROVED.getKey(),
                    StatusEnum.OVERRULE.getKey());
        }
        if (StringUtils.isNotBlank(bizDpProductPageParam.getType())) {
            queryWrapper.like("type",bizDpProductPageParam.getType());
        }
        queryWrapper.lambda().orderByDesc(BizDpProduct::getSubmitTime);
        return this.page(page,queryWrapper);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void examine(BizDpProductExamineParam bizDpProductExamineParam) {
        // 必要参数判断
        if (StringUtils.isEmpty(bizDpProductExamineParam.getOperateType()) || StringUtils.isEmpty(bizDpProductExamineParam.getId())) {
            throw new CommonException("缺少必要操作参数");
        }
        BizDpProduct bizDpProduct = queryEntity(bizDpProductExamineParam.getId());
        if (Objects.isNull(bizDpProduct)) {
            throw new CommonException("产品不存在，id值为：{}", bizDpProductExamineParam.getId());
        }
        BizDpProductExamine bizDpProductExamine = new BizDpProductExamine();
        bizDpProductExamine.setId(IdWorker.getIdStr());
        bizDpProductExamine.setProductId(bizDpProductExamineParam.getId());
        // 审核通过，检验prodID是否重复是否符合规则
        if (StringUtils.equals(bizDpProductExamineParam.getOperateType(), YesNoEnum.YES.getKey())) {
            if (StringUtils.isEmpty(bizDpProductExamineParam.getProdId())) {
                throw new CommonException("审核通过，缺少参数prodId");
            }
            // 产品更新 判断prodId是否变更，变更后是否符合规则且不重复
            bizDpProduct.setStatus(StatusEnum.APPROVED.getKey());
            if (!StringUtils.equals(bizDpProduct.getProdId(),bizDpProductExamineParam.getProdId())) {
                String prodId = bizDpProductExamineParam.getProdId();
                BizDpProduct query = this.getOne(Wrappers.lambdaQuery(BizDpProduct.class).eq(BizDpProduct::getProdId, prodId));
                if (!Objects.isNull(query)) {
                    throw new CommonException("ProdID已存在，请修改后重新审核");
                }
                bizDpProduct.setProdId(prodId);
            }
            bizDpProductExamine.setOperateType(ExamineEnum.APPROVED.getKey());
        }
        // 审核不通过，存储驳回原因
        if (StringUtils.equals(bizDpProductExamineParam.getOperateType(), YesNoEnum.NO.getKey())) {
            if (StringUtils.isEmpty(bizDpProductExamineParam.getExamineContent())) {
                throw new CommonException("审核驳回，缺少参数驳回原因");
            }
            bizDpProduct.setStatus(StatusEnum.OVERRULE.getKey());
            bizDpProductExamine.setOperateType(ExamineEnum.OVERRULE.getKey());
            bizDpProductExamine.setExamineContent(bizDpProductExamineParam.getExamineContent());
        }
        this.updateById(bizDpProduct);
        bizDpProductExamineService.save(bizDpProductExamine);
    }

    @Override
    public List<String> examineList(BizDpProductIdParam bizDpProductIdParam) {
        String id = bizDpProductIdParam.getId();
        BizDpProduct bizDpProduct = queryEntity(id);
        if (Objects.isNull(bizDpProduct)) {
            throw new CommonException("产品不存在，请返回列表刷新重试");
        }
        List<BizDpProductExamine> list = bizDpProductExamineService.list(new QueryWrapper<BizDpProductExamine>().lambda()
                .eq(BizDpProductExamine::getProductId, id)
                .orderByDesc(BizDpProductExamine::getCreateTime));
        List<String> examineList = new ArrayList<>();
        if (!list.isEmpty()) {
            list.forEach(bizDpProductExamine -> {
                String chineseDate = DateUtil.formatChineseDate(bizDpProductExamine.getCreateTime(), false, true);
                ExamineEnum examineEnum = ExamineEnum.getByKey(bizDpProductExamine.getOperateType());
                if (Objects.isNull(examineEnum)) {
                    return;
                }
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(chineseDate);
                stringBuilder.append(" ");
                stringBuilder.append(examineEnum.getValue());
                if (StringUtils.equals(bizDpProductExamine.getOperateType(),ExamineEnum.OVERRULE.getKey())) {
                    stringBuilder.append(" ");
                    stringBuilder.append(bizDpProductExamine.getExamineContent());
                }
                examineList.add(stringBuilder.toString());
            });
        }
        return examineList;
    }

    @Override
    public Map<String, Tree> getTreeList(BizDpProductTreeParam bizDpProductTreeParam) {
        List<Tree<String>> tree = tree(bizDpProductTreeParam);
        List<Tree> treeList = JSON.parseArray(JSON.toJSONString(tree),Tree.class);
        List<Tree> result = new ArrayList<>();
        for (Tree root : treeList) {
            recursionTreeToList(result,root);
        }
        Map<String, Tree> map = new HashMap<>();
        for (Tree treeResult : result) {
            map.put(treeResult.getId().toString(),treeResult);
        }
        return map;
    }

    public void recursionTreeToList(List<Tree> result, Tree root) {
        if (!Objects.isNull(root)) {
            result.add(root);
        }

        if (CollectionUtils.isEmpty(root.getChildren())) {
            return;
        }
        List<Tree> children = JSON.parseArray(JSON.toJSONString(root.getChildren()),Tree.class);
        for (Tree child : children) {
            this.recursionTreeToList(result, child);
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submit(BizDpProductIdParam bizDpProductIdParam) {
        BizDpProduct bizDpProduct = queryEntity(bizDpProductIdParam.getId());
        if (Objects.isNull(bizDpProduct)) {
            throw new CommonException("产品不存在，id值为：{}", bizDpProductIdParam.getId());
        }
        if (StringUtils.equals(bizDpProduct.getStatus(),StatusEnum.TO_BE_REVIEWED.getKey())
                || StringUtils.equals(bizDpProduct.getStatus(),StatusEnum.APPROVED.getKey())) {
            throw new CommonException("当前状态不允许提交审核，请刷新重试");
        }
        bizDpProduct.setStatus(StatusEnum.TO_BE_REVIEWED.getKey());
        bizDpProduct.setSubmitTime(DateUtil.date());
        updateById(bizDpProduct);
        BizDpProductExamine bizDpProductExamine = new BizDpProductExamine();
        bizDpProductExamine.setId(IdWorker.getIdStr());
        bizDpProductExamine.setProductId(bizDpProduct.getId());
        bizDpProductExamine.setOperateType(ExamineEnum.SUBMIT.getKey());
        bizDpProductExamineService.save(bizDpProductExamine);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void withdraw(BizDpProductIdParam bizDpProductIdParam) {
        BizDpProduct bizDpProduct = queryEntity(bizDpProductIdParam.getId());
        if (Objects.isNull(bizDpProduct)) {
            throw new CommonException("产品不存在，id值为：{}", bizDpProductIdParam.getId());
        }
        if (!StringUtils.equals(bizDpProduct.getStatus(),StatusEnum.TO_BE_REVIEWED.getKey())) {
            throw new CommonException("当前状态不允许撤回，请刷新重试");
        }
        bizDpProduct.setStatus(StatusEnum.TO_BE_SUBMITTED.getKey());
        updateById(bizDpProduct);
        BizDpProductExamine bizDpProductExamine = new BizDpProductExamine();
        bizDpProductExamine.setId(IdWorker.getIdStr());
        bizDpProductExamine.setProductId(bizDpProduct.getId());
        bizDpProductExamine.setOperateType(ExamineEnum.WITHDRAW.getKey());
        bizDpProductExamineService.save(bizDpProductExamine);
    }

    @Override
    public BizDpProduct getByProdId(BizDpProductProdIdParam bizDpProductProdIdParam) {
        BizDpProduct query = this.getOne(Wrappers.lambdaQuery(BizDpProduct.class).eq(BizDpProduct::getProdId, bizDpProductProdIdParam.getProdId()));
        return query;
    }

    @Override
    public BizProCategoryDetailResult getCategoryDictDetail(String categoryDictId) {
        CommonResult commonResult = restTemplateHelper.getCategoryDictDetail(categoryDictId);
        if (!commonResult.getCode().equals(CommonResult.CODE_SUCCESS)) {
            throw new CommonException(commonResult.getCode(), commonResult.getMsg());
        }
        String  json = JSON.toJSONString(commonResult.getData());
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        return JSON.parseObject(json, BizProCategoryDetailResult.class);
    }

    @Override
    public Page<BizDpProduct> listByPage(BizDpProductPageParam bizDpProductPageParam) {
        Page<BizDpProduct> page = new Page<>(bizDpProductPageParam.getCurrent(), bizDpProductPageParam.getSize());
        QueryWrapper<BizDpProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(BizDpProduct::getId, BizDpProduct::getBrand, BizDpProduct::getName,
                BizDpProduct::getStatus,BizDpProduct::getType,BizDpProduct::getCategoryDictParentId,BizDpProduct::getCreateTime,
                BizDpProduct::getProdId,BizDpProduct::getModel,BizDpProduct::getBrand);
        SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
        List<String> roleCodeList = loginUser.getRoleCodeList();
        // 判断当前登录用户是否只为企业用户
        if (roleCodeList.size() == 1 && roleCodeList.contains(ROLE_CODE)) {
            queryWrapper.lambda()
                    .and(queryWrapper1 -> queryWrapper1
                                    .eq(BizDpProduct::getCreateUser, loginUser.getId())
                                    .or().eq(BizDpProduct::getStatus,StatusEnum.APPROVED.getKey() )
                            )
                    .orderByDesc(BizDpProduct::getCreateTime);
            return this.page(page,queryWrapper);
        } else {
            queryWrapper.lambda().orderByDesc(BizDpProduct::getCreateTime);
            return this.page(page,queryWrapper);
        }

    }

    @Override
    public void profileDownload(BizDpProduct bizDpProduct, HttpServletResponse response)  {
        File zip = null;
        if (StringUtils.equals(bizDpProduct.getSupportProximityDiscovery(), YesNoEnum.YES.getKey())) {
            zip = genProfileFile();
            try {
                FileUtils.cleanDirectory(new File("/data"));
            } catch (IOException e) {
                log.error("删除文件失败:", e);
            }
        } else {
            zip = genDeviceInfoFile();
            try {
                FileUtils.cleanDirectory(new File(DEVICE_INFO_PATH));
            } catch (IOException e) {
                log.error("删除文件失败:", e);
            }
        }
        ZipFileUtils.downloadAnyFile(zip, response);
    }

    private File genDeviceInfoFile() {
        // 导出到设备库
        List<DevicesInformationResult> results = new ArrayList<>();
        LambdaQueryWrapper<BizDpProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BizDpProduct::getStatus, StatusEnum.APPROVED.getKey());
        List<BizDpProduct> list = list(lambdaQueryWrapper);
        File path = new File(DEVICE_INFO_ASSETS_PATH);

        File file = new File(DEVICE_INFO_JSON);
        try {
            if (!path.exists()) {
                path.mkdirs();
            }
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
        } catch (IOException e) {
            log.error("创建文件失败", e);
        }
        try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(DEVICE_INFO_JSON))) {
            for (BizDpProduct dpProduct : list) {
                DevicesInformationResult devicesInformationResult = new DevicesInformationResult();
                List<String> industryId = new ArrayList<>();
                industryId.add(dpProduct.getCategoryDictId());
                devicesInformationResult.setIndustryId(industryId);
                List<String> industryName = new ArrayList<>();
                industryName.add(dpProduct.getType());
                devicesInformationResult.setIndustryName(industryName);

                devicesInformationResult.setManufacturerId("");
                devicesInformationResult.setManufacturerName("");
                devicesInformationResult.setManufacturerFullName("");

                devicesInformationResult.setDeviceTypeId(dpProduct.getCategoryDictId());
                devicesInformationResult.setDeviceTypeName(dpProduct.getType());
                devicesInformationResult.setProductID(dpProduct.getProdId());
                devicesInformationResult.setDeviceName(dpProduct.getName());
                devicesInformationResult.setOsTypeName(dpProduct.getOsType());
                devicesInformationResult.setOsVersion(dpProduct.getOsSystemVersion());
                devicesInformationResult.setTypicalService("");
                List<String> icons = new ArrayList<>();
                String iconA = dpProduct.getProdId() + "/iconA.png";
                String iconB = dpProduct.getProdId() + "/iconB.png";
                icons.add(iconA);
                icons.add(iconB);
                File assets = new File(DEVICE_INFO_ASSETS_PATH + "/" + dpProduct.getProdId() );
                if (!assets.exists()) {
                    assets.mkdirs();
                }
                if (StringUtils.isNotBlank(dpProduct.getImageBase64())) {
                    String imageASt = dpProduct.getImageBase64().substring(22);
                    BufferedImage imageA = ImgUtil.toImage(imageASt);
                    if (imageA != null) {
                        File outputFile = new File(DEVICE_INFO_ASSETS_PATH + "/" + iconA);
                        try {
                            ImageIO.write(imageA, "PNG", outputFile);
                        } catch (IOException e) {
                            log.error("保存图片时发生错误", e);
                        }
                    } else {
                        log.error("转换失败，得到的图像为空");
                    }
                }
                if (StringUtils.isNotBlank(dpProduct.getHighImageBase64())) {
                    String imageBSt = dpProduct.getHighImageBase64().substring(22);
                    BufferedImage imageB = ImgUtil.toImage(imageBSt);
                    if (imageB != null) {
                        File outputFile = new File(DEVICE_INFO_ASSETS_PATH + "/" + iconB);
                        try {
                            ImageIO.write(imageB, "PNG", outputFile);
                        } catch (IOException e) {
                            log.error("保存图片时发生错误", e);
                        }
                    } else {
                        log.error("转换失败，得到的图像为空");
                    }
                }
                devicesInformationResult.setDeviceIcons(icons);
                devicesInformationResult.setDeviceModel(dpProduct.getModel());
                // 生成profile文件
                devicesInformationResult.setDeviceProfile("");
                devicesInformationResult.setIndustryNameEn(new ArrayList<>());
                devicesInformationResult.setManufacturerNameEn("");
                devicesInformationResult.setManufacturerFullNameEn("");
                devicesInformationResult.setDeviceTypeNameEn("");
                devicesInformationResult.setDeviceNameEn(dpProduct.getNameEn());
                devicesInformationResult.setOsTypeNameEn(dpProduct.getOsTypeEn());
                devicesInformationResult.setTypicalServiceEn("");
                if (StringUtils.isNotBlank(dpProduct.getPinCodeMethod())) {
                    devicesInformationResult.setPinType(Integer.parseInt(dpProduct.getPinCodeMethod()));
                }
                devicesInformationResult.setOHConnectCertified(false);
                results.add(devicesInformationResult);
            }
            bufferedWriter.write(JSON.toJSONString(results));
            bufferedWriter.newLine();
            bufferedWriter.flush();
            // 生成version文件
            File versionFile = new File(DEVICE_INFO_VERSION);
            if (!versionFile.exists()) {
                try {
                    versionFile.createNewFile();
                } catch (IOException e) {
                    log.error("创建文件失败", e);
                }
            }
            try (BufferedWriter versionBuffer = new BufferedWriter(new FileWriter(DEVICE_INFO_VERSION))) {
                String version = devConfigApi.getValueByKey(DEVICE_INFO_VERSION_KEY);
                versionBuffer.write(version);
                versionBuffer.newLine();
                versionBuffer.flush();
            } catch (Exception e) {
                log.error("保存文件时发生错误", e);
            }

        }catch (IOException e) {
            log.error("创建文件失败", e);
        }
        FileUtil.del(new File(DEVICE_INFO_ZIP));
        return ZipUtil.zip(DEVICE_INFO_PATH);
    }

    private File genProfileFile() {
        // 支持靠近发现功能的导出文件可以导入到智慧生活平台
        List<BizDpProductSettingResult> results = new ArrayList<>();
        LambdaQueryWrapper<BizDpProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BizDpProduct::getSupportProximityDiscovery, YesNoEnum.YES.getKey());
        lambdaQueryWrapper.eq(BizDpProduct::getStatus, StatusEnum.APPROVED.getKey());
        List<BizDpProduct> list = list(lambdaQueryWrapper);
        File path = new File(DATA_IMAGE_PATH);
        File file = new File(DATA_PROFILE_PATH);
        try {
            if (!path.exists()) {
                path.mkdirs();
            }
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
        } catch (IOException e) {
            log.error("创建文件失败", e);
        }
        try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(DATA_PROFILE_PATH))) {
            for (BizDpProduct dpProduct : list) {
                String icon = dpProduct.getProdId() + "/icon.png";
                BizDpProductSettingResult result = new BizDpProductSettingResult();
                result.setDeviceId(dpProduct.getProdId());
                result.setDeviceTypeId(dpProduct.getCategoryDictId());
                result.setDeviceNameSpreading(dpProduct.getName());
                result.setDeviceNameSpreadingEn(dpProduct.getNameEn());
                result.setIcon(icon);
                result.setLink(dpProduct.getDeepLink());
                result.setBundleName(dpProduct.getAppPackageName());
                result.setAppIdentifier(dpProduct.getAppIdentifier());
                results.add(result);
                // 生成照片文件
                if (StringUtils.isNotBlank(dpProduct.getImageBase64())) {
                    String imageASt = dpProduct.getImageBase64().substring(22);
                    BufferedImage image = ImgUtil.toImage(imageASt);
                    if (image != null) {
                        File imagePath = new File(DATA_IMAGE_PATH + "/" + dpProduct.getProdId() );
                        if (!imagePath.exists()) {
                            imagePath.mkdirs();
                        }
                        File outputFile = new File(DATA_IMAGE_PATH + "/" + icon);
                        if (!outputFile.exists()) {
                            try {
                                outputFile.createNewFile();
                                ImageIO.write(image, "PNG", outputFile);
                            } catch (IOException e) {
                                log.error("创建文件失败", e);
                            }
                        }
                    } else {
                        log.error("转换失败，得到的图像为空");
                    }
                }
            }
            bufferedWriter.write(JSON.toJSONString(results));
            bufferedWriter.newLine();
            bufferedWriter.flush();
            // 生成version文件
            File versionFile = new File(DATA_VERSION_PATH);
            if (!versionFile.exists()) {
                try {
                    versionFile.createNewFile();
                } catch (IOException e) {
                    log.error("创建文件失败", e);
                }
            }
            try (BufferedWriter versionBuffer = new BufferedWriter(new FileWriter(DATA_VERSION_PATH))) {
                String version = devConfigApi.getValueByKey(DATA_VERSION_KEY);
                versionBuffer.write(version);
                versionBuffer.newLine();
                versionBuffer.flush();
            } catch (Exception e) {
                log.error("保存文件时发生错误", e);
            }
        } catch (IOException e) {
            log.error("保存文件时发生错误", e);
        }
        FileUtil.del(new File(DATA_ZIP));
        return ZipUtil.zip(DATA_PATH);
    }




}
